import { FC, useEffect, useState } from "react";

// 引入资源
import styles from './styles.module.scss'
import { Breadcrumb, Checkbox } from 'antd';
import { Link, useSearchParams, useNavigate } from "react-router-dom";

// 引入类型
import { SubDataType, SelectCategorySubPostData, Good } from "../../api/CategorySub/type";

// 引入请求
import { reqCategorySub, postSelectCategorySub } from "../../api/CategorySub";
import classNames from "classnames";

const CategorySub: FC = () => {

    const [Properties, SetProperties] = useState<SubDataType>()
    const [Goods, SetGoods] = useState<Good[]>()
    const [sortMethod, SetsortMethod] = useState<string>('默认排序')

    let PostData: SelectCategorySubPostData = {
        page: 1,
        pageSize: 20,
        categoryId: '',
        brandId: '',
        attrs: [],
        inventory: false,
        onlyDiscount: false,
        sortField: '',
        sortMethod: '',
    }
    // 选中的属性
    const [SelectedProp, SetSelectedProp] = useState<any>({ '品牌': '全部' })
    const [searchParams] = useSearchParams()
    const id = searchParams.get('id')
    const Navigate = useNavigate()



    // 添加选中的属性
    const addSelectedProp = (category: string, value: string, brandId: string | null = null) => {
        SetSelectedProp((preState: any) => {
            const newAttrs = {
                ...preState,
                [category]: value
            };
            PostData.attrs = newAttrs
            PostData.brandId = brandId
            // 请求数据
            postCategorySubFilter()
            return newAttrs
        })

    }


    const getCategorySub = (id: string) => {
        reqCategorySub(id).then((res) => {
            SetProperties(res.result)
            // 商品
            SetGoods(res.result.goods)
            res.result.saleProperties.forEach((prop) => {
                SetSelectedProp((pre: any) => (
                    {
                        ...pre,
                        [prop.name]: '全部'
                    }
                ))
            })

        })
    }

    const postCategorySubFilter = () => {
        let attrs = []
        for (const [groupName, propertyName] of Object.entries(PostData.attrs)) {
            if (groupName !== '品牌' && propertyName != '全部') {
                attrs.push({
                    groupName,
                    propertyName,
                })
            }
        }
        PostData.attrs = attrs

        postSelectCategorySub(PostData).then((res) => {
            // 过滤后商品
            SetGoods(res.result.items)
        })
    }

    // 跳转商品详细

    const goToGoodsInfo = (id: string) => {
        Navigate(`/product?id=${id}`, {
            replace: false
        })
    }



    useEffect(() => {
        getCategorySub(id as string)

        return () => {

        }
    }, [id])

    return (
        <div className={styles.CategorySub}>
            {/* 面包屑 */}
            <div className={styles.bread}>
                <Breadcrumb
                    items={[
                        {
                            title: <Link to={'/home'}>首页</Link>,
                        },
                        {
                            title: <Link to={`/category?id=${Properties?.parentId}`}>{Properties?.parentName}</Link>,
                        },
                        {
                            title: Properties?.name,
                        },
                    ]}
                />
            </div>
            {/* 筛选 */}
            <div className={styles.select}>
                <div>
                    <span className={styles.head}>品牌:</span>
                    <div className={styles.body}>
                        <span onClick={() => {
                            addSelectedProp('品牌', '全部')
                        }} className={classNames(styles.brand, { [styles.active]: SelectedProp.品牌 === '全部' })}>全部</span>
                        {
                            Properties?.brands.map((brand) => {
                                return (
                                    <span key={brand.id} onClick={() => {
                                        addSelectedProp('品牌', brand.name, brand.id)
                                    }} className={classNames(styles.brand, { [styles.active]: SelectedProp.品牌 === brand.name })}>
                                        {brand.name}
                                    </span>
                                )
                            })
                        }
                    </div>
                </div>
                {
                    Properties?.saleProperties.map((property) => {
                        return (
                            <div key={property.id}>
                                <span className={styles.head}>{property.name}:</span>
                                <div className={styles.body}>
                                    <span onClick={() => {
                                        addSelectedProp(property.name, '全部')
                                    }} className={classNames(styles.property, { [styles.active]: SelectedProp[property.name] === '全部' })}>全部</span>
                                    {
                                        property?.properties.map((p) => {
                                            return (
                                                <span key={p.id} title={p.name} onClick={() => {
                                                    addSelectedProp(property.name, p.name)
                                                }} className={classNames(styles.property, { [styles.active]: SelectedProp[property.name] === p.name })}>
                                                    {p.name}
                                                </span>
                                            )
                                        })
                                    }
                                </div>
                            </div>
                        )
                    })
                }
            </div>
            {/* 商品展示 */}
            <div className={styles.showGoods}>
                <div className={styles.sort}>
                    <span className={classNames({ [styles.active]: sortMethod === '默认排序' })} onClick={() => {
                        SetsortMethod('默认排序')


                    }}>默认排序</span>
                    <span className={classNames({ [styles.active]: sortMethod === '最新商品' })} onClick={() => {
                        SetsortMethod('最新商品')
                        PostData.sortField = 'publishTime'
                        postCategorySubFilter()
                    }}>最新商品</span>
                    <span className={classNames({ [styles.active]: sortMethod === '最高人气' })} onClick={() => {
                        SetsortMethod('最高人气')
                        PostData.sortField = 'orderNum'
                        postCategorySubFilter()
                    }}>最高人气</span>
                    <span className={classNames({ [styles.active]: sortMethod === '评论最多' })} onClick={() => {
                        SetsortMethod('评论最多')
                        PostData.sortField = 'evaluateNum'
                        postCategorySubFilter()
                    }}>评论最多</span>
                    <span className={classNames({ [styles.active]: sortMethod === '价格排序' })} onClick={() => {
                        SetsortMethod('价格排序')
                        PostData.sortField = 'price'
                        PostData.sortMethod = 'desc'
                        postCategorySubFilter()
                    }}>价格排序</span>
                    <div>
                        <Checkbox onChange={(e) => {
                            PostData.inventory = e.target.checked
                            postCategorySubFilter()

                        }} >仅显示有货商品</Checkbox>
                        <Checkbox onChange={(x) => {
                            PostData.onlyDiscount = x.target.checked
                            postCategorySubFilter()
                        }} >仅显示特惠商品</Checkbox>
                    </div>
                </div>
                <div className={styles.content}>
                    {
                        Goods?.map((good) => {
                            return (
                                <li className={styles.goods} key={good.id} onClick={() => {
                                    goToGoodsInfo(good.id)
                                }}>
                                    <img src={good.picture} alt="" />
                                    <div>
                                        <span title={good.name}>{good.name}</span>
                                        <span title={good.desc}>{good.desc}</span>
                                        <span>￥{good.price}</span>
                                    </div>
                                </li>
                            )
                        })
                    }
                </div>
            </div>
        </div>
    )
}

export default CategorySub